package com.bds.btcdc.adapter.zb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.api.model.Result;
import com.bds.btcdc.model.*;
import com.bds.btcdc.service.CoinPairExchangesService;
import com.bds.btcdc.util.Const;
import com.bds.btcdc.util.SpringContextHolder;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.simp.stomp.StompSession;

import java.net.URI;
import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by DongChenchen on 2018/4/9 0009 ZB的WebSocket客戶端，接受ZB的行情更新推送
 */
public class ZBDepthReceiver extends WebSocketClient {
	private Logger log = LoggerFactory.getLogger(getClass());
	private final static DecimalFormat df = new DecimalFormat("#0.0000");
	private static final DecimalFormat df2 = new DecimalFormat("#0.0000");
	private final static String EXCHANGE = "ZB";
	private StompSession session;
	private List<CoinPairExchanges> zb_pairs;
	private CoinPairExchangesService exchangesService;

	public ZBDepthReceiver(StompSession session, URI serverURI, List<CoinPairExchanges> zb_pairs) {
		super(serverURI);
		this.session = session;
		this.zb_pairs = zb_pairs;
		this.exchangesService = SpringContextHolder.getBean(CoinPairExchangesService.class);
	}

	public ZBDepthReceiver(URI serverUri, Draft draft) {
		super(serverUri, draft);
	}

	public ZBDepthReceiver(URI serverURI) {
		super(serverURI);
	}

	@Override
	public void onOpen(ServerHandshake handshakedata) {
		for (CoinPairExchanges pair_exchanges : zb_pairs) {
			String pair_code = pair_exchanges.getPair_code().replace("_","");
			String dataMsg = "{'event':'addChannel','channel':'" +pair_code+ "_depth'}";
			send(dataMsg);
		}
		log.info("######### ZB 获取市场深度  连接成功 #############");
	}

	@Override
	public void onClose(int code, String reason, boolean remote) {
		log.info("ZB 连接关闭,code： " + code + " 异常信息：" + reason);
//		if (code == -1) {
			new Thread() {
				@Override
				public void run() {
					try {
						Thread.sleep(Const.RE_CONN_TIME);
						log.info("ZB 重新建立连接........");
						new ZBDepthReceiver(session, new URI(Const.ZB.WS_URL), zb_pairs).connect();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.start();
//		}
	}

	/**
	 * @param message
	 *            { "channel": "ltcbtc_ticker",当前请求的channel "date":
	 *            "1472800466093",返回数据时服务器时间 "no": 245539, "ticker": { "buy":
	 *            "3826.94",买一价 "high": "3838.22",最高价 "last": "3826.94",最新成交价
	 *            "low": "3802.0",最低价 "sell": "3828.25",卖一价 "vol":
	 *            "90151.83"成交量(最近的24小时) }
	 */
	@Override
	public synchronized void onMessage(String message) {
		try {
//			log.info("ZB 市场深度更新...");
			Result ret = new Result();
			JSONObject json= JSON.parseObject(message);
			String channel=json.getString("channel");
			String pair = channel.split("_")[0];
			String btcPair = exchangesService.getBtcPair(Const.ZB.EXCHANGE, pair);
			MarketDepth depth=new MarketDepth();
				depth.setExchange(Const.ZB.EXCHANGE);
				depth.setPair(btcPair);
			List<Order> bid_list=new ArrayList<>();
			JSONArray bids=json.getJSONArray("bids");
			for (int i = 0; i < 5; i++) {	//深度取到买5
				JSONArray pair_amount = bids.getJSONArray(i);
				Order order=new Order();
				order.setPrice(df.format(pair_amount.getBigDecimal(0)));
				order.setAmount(df2.format(pair_amount.getBigDecimal(1)));
				bid_list.add(order);
			}
			depth.setBids(bid_list);

			List<Order> ask_list=new ArrayList<>();
			JSONArray asks=json.getJSONArray("asks");
			for (int i = 0; i < 5; i++) {
				JSONArray pair_amount = asks.getJSONArray(i);
				Order order=new Order();
				order.setPrice(df.format(pair_amount.getBigDecimal(0)));
				order.setAmount(df2.format(pair_amount.getBigDecimal(1)));
				ask_list.add(order);
			}
			depth.setAsks(ask_list);

			ret.setCode(Const.SUC);
			ret.setData(depth);
			if (session != null) {
				// 推到btc-web主题
				synchronized (session) {
					session.send(Const.ZB.DEPTH_TOPIC, JSONObject.toJSONString(ret).getBytes());
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public void onMessage(ByteBuffer message) {
		log.info("received ByteBuffer");
	}

	@Override
	public void onError(Exception ex) {
		log.info("an error occurred:" + ex);
	}

	// 测试Receiver
	public static void main(String[] args) throws Exception {
		new ZBDepthReceiver(new URI("wss://api.zb.com:9999/websocket")).connect();
	}
}